import Vue from "vue";
import VueRouter from "vue-router";
import jwtDecode from "jwt-decode";

const Login = () => import("@/views/Login.vue");
const Home = () => import("@/views/Home.vue");
const FundList = () => import("@/views/fund/FundList.vue");

Vue.use(VueRouter);

const routes = [
  { path: "/login", component: Login },
  {
    path: "/home",
    component: Home,
    children: [
      { path: "fundlist", component: FundList }, //子路由的path前面不能有/
    ],
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

//前置路由守卫
router.beforeEach((to, from, next) => {
  //1.login页面，任何时候都可以访问
  if (to.path === "/login") {
    next();
  }

  //非login页面：登录之后才能访问
  if (to.path !== "/login") {
    let token = sessionStorage.getItem("token");

    if (!token) {
      //没有token
      next("/login");
    } else {
      //有token,判断是否失效
      let { exp, name } = jwtDecode(token);
      let nowtime = new Date().getTime();
      nowtime = Math.floor(nowtime / 1000);
      if (exp - nowtime >= 0) {
        next();
      } else {
        next("/login");
      }
    }
  }
});

export default router;
